/**
 * Created by 13576 on 2017/11/1.
 * 为了0416迭代上线，重构此文件
 */
import React from 'react';
import { connect } from 'react-redux';
import {
  Button, Badge, Popover, Dropdown, Menu, Icon,
  Modal, Upload, message, Table
} from 'antd';
import menuRoute from 'routes/menuRoute';
import SearchArea from 'components/search-area';
import { messages } from "share/common";
import companyMaintainService from 'containers/enterprise-manage/company-maintain/company-maintain.service';
import config from 'config';
import moment from "moment";
import ExportModal from 'components/template/export-modal/export-modal';
import ImportErrInfo from 'components/template/import-err-info';
import FileSaver from 'file-saver';
import 'styles/enterprise-manage/company-maintain/company-maintain.scss';
import ResizeTable from 'components/resize-table'

class CompanyMaintain extends React.Component {
  constructor(props) {
    super(props);
    this.columnOverflowStyle = {
      wordWrap: 'break-word',
      wordBreak: 'break-word',
      textOverflow: 'ellipsis',
      overflow: 'hidden'
    };
    this.state = {
      showImportPersonModel: false,
      progressImportErrInfo: 1,
      showImportErrInfo: false,
      transactionOID: null,
      errorsList: [
        {
          line: "",
          msg: ""
        },
      ],

      fileList: [],
      flieUploading: false,//文件是否正在上传
      downLoadTempList: [
        {
          type: 1,
          downloading: false,
          name: messages('enterprise-manage.key20'/*公司信息导入模板*/)
        },
        {
          type: 2,
          downloading: false,
          name: messages('enterprise-manage.key21'/*银行信息导入模板*/)
        },
      ],
      loading: true,
      data: [],
      params: {},
      searchParams: {
        name: "",
        companyCode: "",
        setOfBooksId: "",
        legalEntityId: ""
      },
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchForm: [
        {
          type: 'select',
          id: 'setOfBooksId',
          label: messages('enterprise-manage.key22'/*账套*/),
          options: [],
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          method: 'get',
          labelKey: 'setOfBooksName',
          valueKey: 'id',
          getParams: {roleType: 'TENANT'},
          renderOption: option => (option.setOfBooksCode + "-" + option.setOfBooksName)
        },
        {
          type: 'select',
          id: 'legalEntityId',
          label: messages('enterprise-manage.key23'/*法人*/), /*法人*/
          options: [],
          getUrl: `${config.baseUrl}/api/all/legalentitys`,
          method: 'get',
          labelKey: 'entityName',
          valueKey: 'id',
        },
        {
          type: 'input',
          id: 'companyCode',
          label: messages('enterprise-manage.key24'/*公司代码*/), /*公司代码*/
        },
        {
          type: 'input',
          id: 'name',
          label: messages('enterprise-manage.key25'/*公司名称*/), /*公司名称*/
        },
      ],
      columns: [
        {
          title: messages('enterprise-manage.key24'/*公司代码*/),
          dataIndex: 'companyCode',
          fixed: 'left',
          width: 150,
          render: desc => (<div className={'codeStyle'}><Popover content={desc}>{desc ? desc : "-"}</Popover></div>)
        },
        {
          title: messages('enterprise-manage.key25'/*公司名称*/),
          dataIndex: 'name',
          fixed: 'left',
          width: 200,
          render: desc => (<div className={'nameStyle'}><Popover content={desc}>{desc ? desc : "-"}</Popover></div>)
        },
        {
          title: messages('enterprise-manage.key26'/*账套*/),
          dataIndex: 'setOfBooksName',
          // width: 200,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('enterprise-manage.key23'/*法人*/),
          key: "legalEntityName",
          dataIndex: 'legalEntityName',
          width: 200,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('enterprise-manage.key27'/*公司级别*/),
          key: "companyLevelName",
          dataIndex: 'companyLevelName',
          width: 200,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('enterprise-manage.key28'/*上级公司*/),
          key: "parentCompanyName",
          dataIndex: 'parentCompanyName',
          width: 200,
          render: desc => <span><Popover content={desc}>{desc ? desc : "-"}</Popover></span>
        },
        {
          title: messages('enterprise-manage.key29'/*有效日期从*/),
          key: "startDateActive",
          dataIndex: 'startDateActive',
          width: 120,
          render(recode) {
            return <Popover content={!!recode ? moment(recode).format("YYYY-MM-DD") : ""}>
              {!!recode ? moment(recode).format("YYYY-MM-DD") : ""}
            </Popover>
          }
        },
        {
          title: messages('enterprise-manage.key30'/*有效日期至*/),
          key: "endDateActive",
          dataIndex: 'endDateActive',
          width: 120,
          render(recode) {
            return <Popover content={!!recode ? moment(recode).format("YYYY-MM-DD") : "-"}>
              {!!recode ? moment(recode).format("YYYY-MM-DD") : ""}
            </Popover>
          },
        },
        {
          title: messages("common.column.status"),
          dataIndex: 'enabled',
          width: 120,
          render: isEnabled => (
            <Badge status={isEnabled ? 'success' : 'error'}
                   text={isEnabled ? messages("common.status.enable") : messages("common.status.disable")}/>
          )
        },
        {
          title: messages("common.operation"), //操作
          dataIndex: 'operation',
          key: "id",
          fixed: 'right',
          width: 110,
          render: (text, record) => (
            <span>
              <a style={{marginRight: 10}} onClick={(e) => this.handleRowClick(e, record)}>
                {messages("common.detail")}
              </a>
              <a onClick={(e) => this.editItem(e, record)}>
                {messages("common.edit")}
              </a>
            </span>
          )
        }
      ],
      newCompanyMaintainPage: menuRoute.getRouteItem('new-company-maintain', 'key'),       //公司新建
      companyMaintainDetailPage: menuRoute.getRouteItem('company-maintain-detail', 'key'),  //公司详情
    };
  }

  componentDidMount() {
    this.getList();
  }

  //获取公司列表
  getList() {
    this.setState({loading: true});
    let {searchParams, pagination, columns} = this.state;
    for (let paramsName in searchParams) {
      !searchParams[paramsName] && delete searchParams[paramsName];
    }
    searchParams.page = pagination.page;
    searchParams.size = pagination.pageSize;
    companyMaintainService.getCompaniesByOptions(searchParams)
      .then((response) => {
        response.data.map(item => item.key = item.id);
        pagination.total = Number(response.headers['x-total-count']);
        let result = [];
        if(response.data.length) {
          result = this.getAList(response.data[0].customFormValues);
          result && columns.splice(9,0,...result)
        }
        this.setState({
          loading: false,
          data: response.data,
          pagination,
          columns,
        })
      })
  }
  getAList(data) {
    if (data && data.length) {
      let result = data.map( (item,index) => {
        return ({
          key: item.fieldOID,
          title: item.fieldName,
          dataIndex: 'customFormValues',
          width: 150,
          render: customFormValues => {
            let msgKey = customFormValues[index].messageKey;
            let msgValue = customFormValues[index].value;
            let msgName = customFormValues[index].name || customFormValues[index].value;
            return (
              <span>
                <Popover content={msgKey === 'input' ? msgValue : msgName}>
                  {(msgKey === 'input' ? msgValue : msgName) ? (msgKey === 'input' ? msgValue : msgName) : "-"}
                </Popover>
              </span>
            )
          }
        })
      })
      return result
    } else {
      return null;
    }
  }
  //分页点击
  onChangePager = (pagina, filters, sorter) => {
    let {pagination} = this.state;
    pagination.page = pagina.current - 1;
    pagination.current = pagina.current;
    pagination.pageSize = pagina.pageSize;
    this.setState({
      loading: true,
      pagination
    }, () => {
      this.getList();
    })
  };

  //点击搜搜索
  handleSearch = (params) => {
    let {pagination} = this.state;
    pagination.page = 0;
    pagination.current = 1;
    for (let paramsName in params) {
      !params[paramsName] && delete params[paramsName];
    }
    this.setState(
      {
        pagination,
        searchParams: params
      }, () => {
        this.getList();
      });
  };
  //点击清除
  clearHandle = () => {
    let {searchParams} = this.state;
    searchParams.name = "";
    searchParams.companyCode = "";
    this.setState({
        searchParams
      }, () => {
        this.getList();
      });
  }
  //新建
  handleCreate = () => {
    let path = this.state.newCompanyMaintainPage.url.replace(":flag", 'create');
    this.context.router.push(path)
  };
  //添加扩展字段
  handleAddExtendFiled = () => {
    this.context.router.push(menuRoute.getRouteItem('company-maintain', 'key').children.CompanyExtendFiled.url);
  };
  //跳到新增页面，进行编辑
  editItem = (e, record) => {
    //companyOID需要传过去的，过滤本公司需要用
    let path = this.state.newCompanyMaintainPage.url.replace(":companyOID", record.companyOID);
    path = path.replace(":flag", record.id);
    this.context.router.push(path)
  };
  //跳转到详情
  handleRowClick = (e, value) => {
    let path = this.state.companyMaintainDetailPage.url.replace(":companyOId", value.companyOID);
    path = path.replace(":companyId", value.id);
    this.context.router.push(path);
  };

  //渲染下载模板
  renderDownTemp = (list) => {
    return list.map((data) => {
      return (
        <div style={{marginBottom: 10}} key={data.type}>
          <Button
            className='default-color-font'
            style={{border: 'none'}}
            size={'small'}
            icon="download"
            loading={data.downloading}
            onClick={() => {
              this.downloadTemplateByType(data.type)
            }}
          >
            {data.name}
          </Button>
        </div>
      )

    })
  }
  //下载模板
  downloadTemplateByType = (type) => {
    const {downLoadTempList} = this.state;
    downLoadTempList.map(item => {
      if (item.type === type) {
        item.downloading = true
      }
    });
    this.setState({
      downLoadTempList,
    });
    switch (type) {
      case 1: {
        this.downloadCompanyTemplate(type);
        break;
      }
      case 2: {
        this.downloadBankTemplate(type);
        break;
      }
    }
  }

  // 下载公司信息
  downloadCompanyTemplate = (type) => {
    const {downLoadTempList} = this.state;
    companyMaintainService.downloadCompanyTemplate()
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('enterprise-manage.key20'/*公司信息导入模板*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
        downLoadTempList.map(item => {
          if (item.type === type) {
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
      .catch((err) => {
        downLoadTempList.map(item => {
          if (item.type === type) {
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
  };
  // 下载银行信息模板
  downloadBankTemplate = (type) => {
    const {downLoadTempList} = this.state;
    companyMaintainService.downloadBankTemplate()
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        // 银行信息导入模板
        let name = messages('enterprise-manage.key21'/*银行信息导入模板*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
        downLoadTempList.map(item => {
          if (item.type === type) {
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
      .catch((err) => {
        downLoadTempList.map(item => {
          if (item.type === type) {
            item.downloading = false
          }
        });
        this.setState({
          downLoadTempList,
        });
      })
  };

  render() {
    const {loading, searchForm, data, pagination, columns, searchParams} = this.state;
    const props = {
      onRemove: (file) => {
        this.setState(({fileList}) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        //只上传一个
        this.setState(({fileList}) => ({
          fileList: [file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    const menu = (
      <Menu>
        <Menu.Item key={1}>
          <span onClick={this.props.tenantMode && this.personImport}> {messages('enterprise-manage.key31'/*批量导入公司*/)}
          </span>
        </Menu.Item>
      </Menu>
    );
    const menuExport = (
      <Menu>
        <Menu.Item key={1}>
          <ExportModal
            codeCheck={true}
            exportTitle={messages('enterprise-manage.key32'/*公司信息数据*/)}
            exportType="COMPANY"
            exportCondition={{
              "setOfBooksId": searchParams.setOfBooksId,
              "legalEntityId": searchParams.legalEntityId,
              "companyCode": searchParams.companyCode,
              "name": searchParams.name,
            }}
            exportCommand={"company"}
          />
        </Menu.Item>
        <Menu.Item key={2}>
          <ExportModal
            codeCheck={true}
            exportTitle={messages('enterprise-manage.key33'/*银行信息数据*/)}
            exportType="COMPANY"
            exportCondition={{
              "setOfBooksId": searchParams.setOfBooksId,
              "legalEntityId": searchParams.legalEntityId,
              "companyCode": searchParams.companyCode,
              "name": searchParams.name,
            }}
            exportCommand={"company_bank"}
          />
        </Menu.Item>
      </Menu>
    );
    return (
      <div className="company-maintain">
        <SearchArea searchForm={searchForm}
                    clearHandle={this.clearHandle}
                    submitHandle={this.handleSearch}/>
        <div className="table-header">
          <div
            className="table-header-title">
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            <Dropdown.Button overlay={menu}
                             type="primary"
                             onClick={this.handleCreate}
                             className="table-header-button"
            >
              {messages('enterprise-manage.key333')/*新增公司*/}
            </Dropdown.Button>
            <Button type="primary"
                    onClick={this.handleAddExtendFiled}
                    className="table-header-button">
              {messages('enterprise-manage.key400')/*公司扩展字段*/}
            </Button>
            <Dropdown overlay={menuExport} trigger={['click']}>
              <a className="ant-dropdown-link">
                <span>{messages('enterprise-manage.key34'/*导出公司数据*/)}</span>
                <span>&nbsp;&nbsp;<Icon type="down"/></span>
              </a>
            </Dropdown>

          </div>
        </div>
        <Table
          loading={loading}
          dataSource={data}
          columns={loading ? [] : columns}
          pagination={pagination}
          size="middle"
          bordered
          onChange={this.onChangePager}
          scroll={{x: 1700}}
        />


        <Modal
          closable
          width={800}
          className="pm-import-person-modal"
          title={messages('enterprise-manage.key35'/*导入*/)}//导入
          visible={this.state.showImportPersonModel}
          footer={null}
          onCancel={this.cancelImportPerson}
          destroyOnClose={true}
        >
          <div className="import-person-modal-wrap">

            <div className="f-left import-person-modal-left">
              <p className="import-person-left-tips">
                <h4>{messages('enterprise-manage.key36'/*创建模板*/)}</h4>
              </p>
              {
                this.renderDownTemp(this.state.downLoadTempList)
              }
              <div className="download-list-item-a-wrap">
                <a className="download-list-item-a"
                   href="http://helioscloud-uat-static.oss-cn-shanghai.aliyuncs.com/bank_info.xlsx"
                >
                  {/*银行基础数据（录入银行信息时请根据银行数据录入，该文件无须上传）*/}
                  {messages('enterprise-manage.key37'/*银行基础数据（录入银行信息时请根据银行数据录入，该文件无须上传）*/)}
                </a>
              </div>
              <div>
                <div>{messages('enterprise-manage.key38'/*1.点击下载模板*/)}</div>
                <div>{messages('enterprise-manage.key39'/*2.严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}</div>
                <div>{messages('enterprise-manage.key40'/*3.关闭Excel文件后，方可进行数据导入*/)}</div>
              </div>
            </div>
            <div className="f-right import-person-modal-right">
              <div className="import-person-right-tips"> {messages('enterprise-manage.key41'/*上传模板*/)}
              </div>
              <div className="upload-file-wrap">

                <Upload {...props}>
                  <Button>
                    <Icon type="upload"/>
                    {/*选择一个文件*/}
                    {messages('enterprise-manage.key42'/*选择一个文件*/)}
                  </Button>
                </Upload>
                <Button
                  className="upload-file-start"
                  type="primary"
                  onClick={this.handleFileUpload}
                  disabled={this.state.fileList.length === 0}
                  loading={this.state.flieUploading}
                >
                  {/*?上传中:开始上传*/}
                  {this.state.flieUploading ? messages('enterprise-manage.key43'/*上传中*/) : messages('enterprise-manage.key44'/*开始上传*/)}
                </Button>

              </div>
            </div>
            <div className="clear"/>
          </div>
        </Modal>
        <ImportErrInfo
          progress={this.state.progressImportErrInfo}
          cancel={this.hideImportErrInfo}
          exportErrInfo={this.exportFailedLog}
          title={messages('enterprise-manage.key45'/*公司信息导入错误*/)}
          errorsList={this.state.errorsList}
          visible={this.state.showImportErrInfo}/>
      </div>
    )
  }

  //导入
  personImport = () => {
    this.setState({
      showImportPersonModel: true
    })
  };
  cancelImportPerson = () => {
    this.setState({
      showImportPersonModel: false
    })
  };

  handleFileUpload = () => {
    const {fileList} = this.state;
    const formData = new FormData();
    formData.append('file', fileList[0]);
    this.setState({
      uploading: true,
      flieUploading: true,
    });

    companyMaintainService.importCompanyOrBank(formData)
      .then((res) => {
        this.setState({
          fileList: [],
          uploading: false,
          flieUploading: false,
          showImportPersonModel: false,
          transactionOID: res.data.transactionOID
        }, () => {
          this.showImportErrInfo();
          this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
        });
      })
      .catch((res) => {
        this.setState({
          uploading: false,
          flieUploading: false,
        });
      })
  }

  showTransactionLogDialog = (transactionOID) => {
    companyMaintainService.getBatchTransactionLogNew(transactionOID)
      .then((res) => {
        let data = res.data;
        if (data.totalEntities === 0) {
          this.hideImportErrInfo();
          return;
        } else {
          let errors = data.errors;
          let errorsList = this.getErrorDataByerrors(errors);
          let progressImportErrInfo = this.getProgressByData(data);
          this.setState({
            progressImportErrInfo,
            errorsList
          })
          if ((data.successEntities + data.failureEntities) !== data.totalEntities) {
            let gapTime = 500;
            setTimeout(() => {
              //请求频率涉及到一个算法
              this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
            }, gapTime)
          } else {
            this.getList();
            if (this.state.errorsList.length === 0 && this.state.progressImportErrInfo === 100) {
              message.success(messages("common.operate.success"));
              this.hideImportErrInfo();
            }
          }
        }
      })
  }
  //获取百分进度
  getProgressByData = (data) => {
    return Math.round((data.failureEntities + data.successEntities) * 100 / data.totalEntities);
  }
  //通过错误信息，解析成表格
  getErrorDataByerrors = (errs) => {
    let data = [];
    for (let key in errs) {
      let row = {};
      row.line = errs[key];
      if (row.line.length > 1) {
        let _line = [];
        for (let i = 0; i < row.line.length; i++) {
          _line.push(row.line[i]);
          if (i < row.line.length - 1) {
            _line.push(",");
          }
        }
        row.line = _line;
      }
      row.msg = key;
      data.push(row);
    }
    return data;
  }
  //公司信息导入错误
  exportFailedLog = () => {
    companyMaintainService.exportFailedLog(this.state.transactionOID)
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        // 人员导入错误信息
        let name = messages('enterprise-manage.key45'/*公司信息导入错误*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
  }
  //人员导入的错误信息-start
  showImportErrInfo = () => {
    this.setState({
      showImportErrInfo: true
    })
  }
  hideImportErrInfo = () => {
    this.setState({
      showImportErrInfo: false
    })
  }
}

CompanyMaintain.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.login.organization,
    profile: state.login.profile,
    user: state.login.user,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

export default connect(mapStateToProps)(CompanyMaintain);
